/*
 * Copyright 2013-2019 Xia Jun(3979434@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************************
 *                                                                                     *
 *                        Website : http://www.farsunset.com                           *
 *                                                                                     *
 ***************************************************************************************
 */
package com.workcell.workdata.im.service.impl;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.*;
import com.workcell.workdata.im.component.event.ImageUploadEvent;
import com.workcell.workdata.im.configuration.properties.FileOssProperties;
import com.workcell.workdata.im.constant.FileBucket;
import com.workcell.workdata.im.model.misc.OssFile;
import com.workcell.workdata.im.model.vo.UploadSignVO;
import com.workcell.workdata.im.service.FileStoreService;
import com.workcell.workdata.im.util.JSON;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.web.multipart.MultipartFile;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

/**
 * 文件存储在阿里云OSS的策略下 文件管理实现
 */
public class OssFileServiceImpl implements FileStoreService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OssFileServiceImpl.class);

    private static final String META_REF_COUNT = "X-REF-COUNT";

    private final FileOssProperties properties;

    private final OSSClient ossClient;

    @javax.annotation.Resource
    private ApplicationContext applicationContext;

    @javax.annotation.Resource
    private BiFunction<String,String,String> contentTypeParser;

    public OssFileServiceImpl(FileOssProperties properties){
        this.properties = properties;
        CredentialsProvider provider = new DefaultCredentialProvider(properties.getAccessId(),properties.getAccessKey());
        ossClient = new OSSClient(properties.getEndpoint(), provider, new ClientConfiguration());
    }

    @Override
    public void upload(MultipartFile file, String bucket, String key) {

        try {

            OssFile ossFile = OssFile.of(bucket,key);

            PutObjectRequest putRequest = new PutObjectRequest(properties.getBucket(), ossFile.getKey(), file.getInputStream());
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(contentTypeParser.apply(bucket,key));
            metadata.setContentDisposition("attachment;fileName=" + URLEncoder.encode(key, StandardCharsets.UTF_8.name()));
            putRequest.setMetadata(metadata);

            ossClient.putObject(putRequest);

            applicationContext.publishEvent(new ImageUploadEvent(bucket,key));

        } catch(Exception e) {
            LOGGER.error("OSS文件上传失败,bucket:{} key:{}",bucket,key);
        }
    }

    @Override
    public Resource get(String bucket, String key) {

        OssFile ossFile = OssFile.of(bucket,key);

        boolean isDestFileExist = ossClient.doesObjectExist(properties.getBucket(),ossFile.getKey());

        if (isDestFileExist){
            return new UrlResource(getOssFileUrl(bucket,key));
        }

        String defaultFileName =  FileBucket.getDefaultFilename(bucket);
        if (defaultFileName == null){
            return null;
        }

        return new UrlResource(getOssFileUrl(bucket,defaultFileName));
    }

    @Override
    public void delete(String bucket, String key) {

        OssFile ossFile = OssFile.of(bucket,key);

        int count = getReferenceCount(ossFile);

        if (count == 0){
            ossClient.deleteObject(properties.getBucket(), ossFile.getKey());
            return;
        }

        this.addReferenceCount(ossFile,-1);
    }

    @Override
    public void addReferenceCount(String bucket, String key) {
         this.addReferenceCount(OssFile.of(bucket,key),1);
    }

    /**
     * 返回阿里云OSS 客户端直传 签名信息
     * <a href="https://help.aliyun.com/document_detail/31926.html?spm=a2c4g.112718.0.0.392b3967OJMVSY">OSS文档地址</a>
     * @param bucket 目录名
     * @param name 文件名
     * @return 签名信息
     */
    @Override
    public UploadSignVO getUploadSign(String bucket, String name) {
        Date expiration = new Date( System.currentTimeMillis() + 300 * 1000);
        PolicyConditions policyConditions = new PolicyConditions();
        policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, FileUtils.ONE_MB * 50);
        policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, bucket + "/");

        String policy = ossClient.generatePostPolicy(expiration, policyConditions);

        String host = properties.getEndpoint().replace("://",("://" + properties.getBucket() + "."));

        UploadSignVO signVO = new UploadSignVO();
        signVO.addParameter("OSSAccessKeyId",properties.getAccessId());
        signVO.addParameter("policy",Base64.encodeBase64String(policy.getBytes(StandardCharsets.UTF_8)));
        signVO.addParameter("signature",ossClient.calculatePostSignature(policy));
        signVO.addParameter("key",bucket + "/" + name);
        signVO.setHost(host);

        Map<String,String> callbackMap = new HashMap<>();
        callbackMap.put("callbackUrl",properties.getCallbackUrl());
        callbackMap.put("callbackBody","filename=${object}&size=${size}&mimeType=${mimeType}");
        signVO.addParameter("callback",Base64.encodeBase64String((JSON.toJSONString(callbackMap).getBytes())));

        return signVO;
    }



    private int getReferenceCount(OssFile ossFile) {

        ObjectMetadata metadata = getObjectMetadata(ossFile);

        if (metadata == null){
            return 0;
        }

        return Integer.parseInt(metadata.getUserMetadata().getOrDefault(META_REF_COUNT,"0"));
    }

    private void addReferenceCount(OssFile ossFile,int add) {

        ObjectMetadata metadata = getObjectMetadata(ossFile);

        if (metadata == null){
            return;
        }

        int count = Integer.parseInt(metadata.getUserMetadata().getOrDefault(META_REF_COUNT,"0"));

        metadata.addUserMetadata(META_REF_COUNT,String.valueOf(count + add));

        CopyObjectRequest request = new CopyObjectRequest(properties.getBucket(), ossFile.getKey(), properties.getBucket(), ossFile.getKey());

        request.setNewObjectMetadata(metadata);

        ossClient.copyObject(request);
    }

    private ObjectMetadata getObjectMetadata(OssFile ossFile){

        if (!ossClient.doesObjectExist(properties.getBucket(), ossFile.getKey())){
            return null;
        }

        return ossClient.getObjectMetadata(properties.getBucket(), ossFile.getKey());
    }

    /**
     * 这里需要把properties.bucket 设置为公共读
     * @param bucket
     * @param fileName
     * @return
     */
    private URL getOssFileUrl(String bucket,String fileName){
        Date expiration = new Date(System.currentTimeMillis() + 60000);
        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(properties.getBucket(),bucket + "/" + fileName);
        urlRequest.setExpiration(expiration);
        URL url =  ossClient.generatePresignedUrl(urlRequest);
        try {
            /*
             * url.getPath()去掉时间有效期参数，转换为永久有效URL
             */
            return new URL(url.getProtocol(),url.getHost(),url.getPath());
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
